package cn.imokay.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号灯
//6辆车，3个车位
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            int finalI = i+1;
            new Thread(()->{
                //抢占车位
                try {
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    int i1 = new Random().nextInt(5)+1;
                    //设置停车事件
                    TimeUnit.SECONDS.sleep(i1);
                    System.out.println(Thread.currentThread().getName()+"离开了了车位，停了"+i1+"秒");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    //离开后释放车位
                    semaphore.release();
                }
            },"车辆："+finalI).start();

        }

    }
}
